<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/10
 * Time: 10:52
 */

namespace bgb\weixin;
use bgb\Http;

/**
 * 微信公众号
 * Class Official
 * @package bgb\weixin
 */
class Official
{

    use Http;

    protected static $instance;

    const GET_ACCESS_TOKEN = 'https://api.weixin.qq.com/cgi-bin/token'; //获取access_token

    protected $appid;
    protected $appsecret;

    public function __construct($appid, $appsecret)
    {
        $this->appid = $appid;
        $this->appsecret = $appsecret;
    }

    /**
     * 单例支持
     * @param $appid string 公众号appid
     * @param $appsecret string 公众号秘钥
     * @return $this
     */
    public static function getInstance($appid, $appsecret)
    {
        $key = md5('appid:' . $appid . ':appsecret:' . $appsecret . ':official');

        if (!isset(self::$instance[$key])) {
            self::$instance[$key] = new static($appid, $appsecret);
        }

        return self::$instance[$key];

    }

    /**
     * 获取公众号accessToken 有效期为2小时 需要定时维护 新增缓存维护
     * @return mixed
     */
    public function getAccessToken()
    {
        $key = 'appid_access_token:' . $this->appid;

        if (!$accessToken = cache($key)) {
            $result = $this->getRequest(self::GET_ACCESS_TOKEN, [
                'appid' => $this->appid,
                'secret' => $this->appsecret
            ]);

            $accessToken = '';
            if (isset($result['access_token'])) {
                $accessToken = $result['access_token'];

                cache($key, $result['access_token'], 60 * 60 * 2);
            }

        }
        return $accessToken;
    }

}